import React, { useState, useEffect } from 'react';
import styles from './index.less';
import CardCommon from '@/compontents/cardCommon';
import lhTool from 'lh-tool';
import api from '@/http/api';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input, Upload, DatePicker, message } from 'antd';
import moment from 'moment';
import E from 'wangeditor';

let editor: any = null;
export default (props: any) => {
  const { manageId, schoolId } = JSON.parse(sessionStorage.info).userInfo;
  const isAdd = props.history.location.state.isAdd;
  const initData = props.history.location.state.initData;
  const [content, setContent] = useState('');
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 4, span: 16 },
  };
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );
  const [fileList1, seFileList1]: any = useState([]);
  const onchange1 = (e: any) => {
    const fileLists = e.fileList;
    const len = fileLists.length;
    if (e.file.status === 'done') {
      const list: any = [...fileList1].splice(0, len - 1);
      list.push({
        uid: new Date().getTime(),
        url: e.file.response.data.src,
      });
      seFileList1(list);
    } else {
      seFileList1(fileLists);
    }
  };

  const onFinish = (v: any) => {
    if (fileList1.length && editor.txt.html()) {
      const src = fileList1[0].url;
      const params = {
        title: v.title,
        activeTime: lhTool.formatDate.format(
          new Date(v.activeTime),
          'yyyy-MM-dd hh:mm:ss',
        ),
        address: v.address,
        content: editor.txt.html(),
        src,
        intro: v.intro,
        manageId,
        type: 1,
        uSchoolId: schoolId,
      };
      if (isAdd) {
        api.activeAdd(params).then(res => {
          props.history.push({
            pathname: '/active',
          });
        });
      } else {
        api.activeUpdate({ ...params, id: initData.id }).then(res => {
          props.history.push({
            pathname: '/active',
          });
        });
      }
    } else {
      if (!fileList1.length) {
        message.error('请上传活动列表图片');
      }
      if (!editor.txt.html()) {
        message.error('请编写活动详情');
      }
    }
  };

  useEffect(() => {
    editor = new E('#edit');
    editor.config.uploadImgServer = `${process.env.apiUrl}upload/edit`;
    editor.config.onchange = (newHtml: any) => {
      setContent(newHtml);
    };
    editor.create();
    if (!isAdd) {
      seFileList1([
        {
          uid: 1,
          url: initData.src,
        },
      ]);
      editor.txt.html(initData.content);
    }
    return () => {
      editor.destroy();
    };
  }, []);
  return (
    <CardCommon>
      <div className={styles.wrap}>
        <Form
          className={styles.form}
          {...layout}
          name="basic"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            initialValue={isAdd ? '' : moment(new Date(initData.activeTime))}
            label="活动时间"
            name="activeTime"
            rules={[{ required: true, message: '请选择活动时间' }]}
          >
            <DatePicker showTime format="YYYY-MM-DD HH:mm" />
          </Form.Item>
          <Form.Item
            label="活动标题"
            name="title"
            rules={[{ required: true, message: '请输入标题' }]}
            initialValue={isAdd ? '' : initData.title}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="活动简介"
            name="intro"
            rules={[{ required: true, message: '请输入活动简介' }]}
            initialValue={isAdd ? '' : initData.intro}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="活动列表图片"
            name="src"
            rules={[{ required: false, message: '请上传活动列表图片' }]}
          >
            <Upload
              action={process.env.apiUrl + 'upload/image'}
              listType="picture-card"
              fileList={fileList1}
              // onPreview={this.handlePreview}
              onChange={onchange1}
            >
              {fileList1.length >= 1 ? null : uploadButton}
            </Upload>
          </Form.Item>

          <Form.Item
            initialValue={isAdd ? '' : initData.address}
            label="活动地址"
            name="address"
            rules={[{ required: true, message: '请输入活动地址' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            initialValue={isAdd ? '' : initData.address}
            label="活动详情"
            name="content"
            rules={[{ required: false, message: '请输入活动详情' }]}
          >
            <div id="edit"></div>
          </Form.Item>
          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </CardCommon>
  );
};
